import { fork } from 'child_process';
import {
  app,
  BrowserWindow,
  protocol,
  Menu,
  MenuItem,
  ipcMain,
} from 'electron';
import createProtocol from 'umi-plugin-electron-builder/lib/createProtocol';
const path = require('path');

protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } },
]);

let serverProcess;

Menu.setApplicationMenu(null);

function createWindow() {
  // 创建窗口
  const mainWindow = new BrowserWindow({
    width: 1080,
    height: 920,
    title: '会员管理系统',
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    },
  });

  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('http://localhost:8000/');
    mainWindow.webContents.openDevTools();
  } else {
    createProtocol('app');
    mainWindow.loadURL('app://./index.html');
  }
}

app.on('ready', () => {
  createWindow();
  createServerProgress();
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    serverProcess && process.kill(serverProcess.pid);
    app.quit();
  }
});

function openAboutMe() {
  let windowAboutMe = new BrowserWindow({
    width: 1280,
    height: 920,
  });
  windowAboutMe.loadURL('http:youngam.cn');
  windowAboutMe.on('closed', () => {
    windowAboutMe = null;
  });
}

function initMenu() {
  const menu = new Menu();
  menu.append(new MenuItem({ label: '刷新', role: 'reload' }));
  menu.append(new MenuItem({ label: '复制', role: 'copy' }));
  menu.append(new MenuItem({ label: '全选', role: 'selectAll' }));
  menu.append(new MenuItem({ label: '粘贴', role: 'paste' }));
  // if (app.isPackaged) {
  //   menu.append(new MenuItem({ label: '关于作者', click: openAboutMe }));
  // } else {
  //   menu.append(new MenuItem({ label: '开发者工具', role: 'toggleDevTools' }));
  // }
  menu.append(new MenuItem({ label: '开发者工具', role: 'toggleDevTools' }));

  return menu;
}

// 监听右键事件
const contextMenu = initMenu();
ipcMain.on('contextMenu', () => {
  contextMenu.popup();
});

// 创建本地服务进程
function createServerProgress() {
  if (app.isPackaged) {
    serverProcess = fork('../server/index.js', [], {
      cwd: path.join(__dirname, '../server'),
    });
  } else {
    serverProcess = fork(require.resolve('../server/index.js'));
    serverProcess.on('close', (code) => {
      console.log('子线程已经退出', code);
    });
  }
  try {
  } catch (err) {
    console.log(err);
  }
}
